<?php

namespace App\Http\Controllers\Common;

use App\Http\Controllers\Controller;
use App\Services\CodeService;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Validation\Rule;

class CodeController extends Controller
{
    //

    public function code(Request $request, CodeService $codeService)
    {
        $model = $request->model;

        $user = Auth::user();
        switch ($model) {


            case 'mobile':
                $request->validate([$model => ['regex:/^1\d{10}$/i', 'required']]);
                break;
            case 'email':
                $request->validate([$model => ['email', 'required']]);
                break;

            default:
                $request->validate(['account' => ['required', $this->validateAccountField()]]);

        }
        $request->validate(
            [
                'captcha' => ['required', 'captcha'],

            ],
            ['captcha.captcha' => '验证码不正确']
        );

        $codeService->send($request->$model);
        // return response()->json(['message' => '验证码发送成功']);

        return response()->json(['message' => '验证码发送成功']);
    }

    // 获取登录账号类型（表字段）
    protected function username()
    {
        return filter_var(request()->account, FILTER_VALIDATE_EMAIL) ? 'email' : 'mobile';
    }

    //账号验证规则
    protected function validateAccountField()
    {

        return filter_var(request()->account, FILTER_VALIDATE_EMAIL) ? 'email' : 'regex:/^1\d{10}$/i';
    }
}
